﻿using CsharpHttpFileShareUI.WebServer;
using System;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.Drawing;
using System.IO;
using System.Net;
using System.Windows.Forms;
using ZXing;
using ZXing.QrCode;

namespace CsharpHttpFileShareUI
{
    public partial class Form1 : Form
    {
        /// <summary>
        /// HttpServer
        /// </summary>
        private Server Server { get; set; }

        /// <summary>
        /// form构造函数
        /// </summary>
        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Form1_Load窗口初始载入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            this.Text = "Personal File Web Server " + GetLocalIP();

            this.lblAppPath.Text = AppDomain.CurrentDomain.BaseDirectory + "wwwroot";
            if (!Directory.Exists(this.lblAppPath.Text))
            {
                Directory.CreateDirectory(this.lblAppPath.Text);
            }
            if (string.IsNullOrEmpty(this.lblAppPath.Text))
            {
                this.lblAppPath.Text = this.lblAppPath.Text;
            }

            this.lblSharePath.Text = this.lblAppPath.Text + "\\share_file";
            if (!Directory.Exists(this.lblSharePath.Text))
            {
                Directory.CreateDirectory(this.lblSharePath.Text);
            }
        }


        #region Start, Stop
        /// <summary>
        /// btnStart_Click 开始按钮单击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStart_Click(object sender, EventArgs e)
        {
            this.linkLabel1.Text = String.Format("http://{0}:{1}", GetLocalIP(), nudPort.Value);
            MakeQR_CodeAndDisp();

            Start();

        }

        /// <summary>
        /// 生成二维码,显示在 pictureBox1
        /// </summary>
        private void MakeQR_CodeAndDisp()
        {
            BarcodeWriter writer = new BarcodeWriter();
            writer.Format = BarcodeFormat.QR_CODE;
            QrCodeEncodingOptions options = new QrCodeEncodingOptions();
            options.DisableECI = true;
            //设置内容编码
            options.CharacterSet = "UTF-8";
            //设置二维码的宽度和高度
            options.Width = 200;
            options.Height = 200;
            //设置二维码的边距,单位不是固定像素
            options.Margin = 1;
            writer.Options = options;

            Bitmap map = writer.Write(this.linkLabel1.Text);

            this.pictureBox1.Image = map;


        }

        /// <summary>
        /// btnStop_Click 停止按钮单击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStop_Click(object sender, EventArgs e)
        {
            this.linkLabel1.Text = "";
            Stop();
        }

        /// <summary>
        /// func_Start
        /// </summary>
        private void Start()
        {
            try
            {
                Server = new Server((int)nudPort.Value, "/", lblAppPath.Text, IPAddress.Any);

                // Register event handlers
                Server.Started += new EventHandler(ServerStarted);
                Server.Stopped += new EventHandler(ServerStopped);

                Server.Start();
            }
            catch
            {
                string strErrMsg = "Cassini Managed Web Server failed to start listening on port " + nudPort.Value + ".\r\n" +
                           "Possible conflict with another Web Server on the same port.";
                MessageBox.Show(strErrMsg, "CsharpHttpFileShareUI", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// func Stop
        /// </summary>
        private void Stop()
        {
            try
            {
                if (Server != null)
                {
                    Server.Stop();
                }
            }
            finally
            {
                // Unregister event handlers
                if (Server != null)
                {
                    Server.Started -= new EventHandler(ServerStarted);
                    Server.Stopped -= new EventHandler(ServerStopped);
                }

                Server = null;
            }
        }

        /// <summary>
        /// 委托 ServerStopped
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ServerStopped(object sender, EventArgs e)
        {
            this.lblStatusMsg.Text = "CsharpHttpFileShareUI stopped";  // SetStatus(String.Format("{0} stopped", Version.FullName));

            this.linkLabel1.Text = string.Empty; //llaOpenBrowser.Text = String.Empty;

            //EnableInput(true);
        }

        /// <summary>
        /// 委托 ServerStarted
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ServerStarted(object sender, EventArgs e)
        {
            this.lblStatusMsg.Text = "CsharpHttpFileShareUI running on port " + this.nudPort.Value.ToString();  //SetStatus(String.Format("{0} running on port {1}", Version.FullName, nudPort.Value));

            this.linkLabel1.Text = Server.RootUrl;  //llaOpenBrowser.Text = Server.RootUrl;

            //EnableInput(false);
        }

        #endregion

        /// <summary>
        /// func 取得 NetWork IPAddress
        /// </summary>
        /// <returns></returns>
        public string GetLocalIP()
        {
            IPAddress localIp = null;
            try
            {
                IPAddress[] ipArray;
                ipArray = Dns.GetHostAddresses(Dns.GetHostName());
                foreach (var ipAddress in ipArray)
                {
                    if (ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        localIp = ipAddress;
                        break;
                    }
                }
                //localIp = ipArray.First(ip => ip.AddressFamily == AddressFamily.InterNetwork);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.StackTrace + "\r\n" + ex.Message, "错误", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
                //Log.WriteLog(ex);
            }
            if (localIp == null)
            {
                localIp = IPAddress.Parse("127.0.0.1");
            }
            return localIp.ToString();
        }

        /// <summary>
        ///  btnOpenFileDir_Click 打开共享文件夹按钮单击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpenFileDir_Click(object sender, EventArgs e)
        {
            string strSharePath = AppDomain.CurrentDomain.BaseDirectory + "wwwroot\\share_file";
            if (Directory.Exists(strSharePath))
            {
                string[] namell = Directory.GetFiles(strSharePath);
                if (namell.Length > 0)
                {
                    string strFirstFilePath = namell[0];
                    if (File.Exists(strFirstFilePath))
                    {
                        strSharePath = strFirstFilePath;
                    }
                }
            }

            Process p = new Process();
            p.StartInfo.FileName = "explorer.exe";

            p.StartInfo.Arguments = @" /select, " + strSharePath;
            p.Start();

        }

        /// <summary>
        /// 用浏览器打开
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start(this.linkLabel1.Text);
        }
    }
}
